package com.tjhzzx.danfossNiagaraCore;

import com.tjhzzx.danfossNiagaraCore.servlet.impl.BTlsWebServer;
import com.tjhzzx.danfossNiagaraCore.util.Constants;
import com.tridium.hx.BHandheldHxProfile;

import javax.baja.agent.AgentFilter;
import javax.baja.collection.BITable;
import javax.baja.collection.TableCursor;
import javax.baja.file.BFileSystem;
import javax.baja.file.FilePath;
import javax.baja.naming.BOrd;
import javax.baja.naming.OrdQuery;
import javax.baja.sys.BIObject;
import javax.baja.sys.Sys;
import javax.baja.sys.Type;
import java.io.File;
import java.util.logging.Logger;

/**
 * Created by Luc on 2018/11/4.
 * <p>
 * <p>
 * 提供与velocity页面交互的接口
 */

//@NiagaraType
public class BDncHandheldHxProfile extends BHandheldHxProfile {
    private static final Logger LOGGER = Logger.getLogger(BDncHandheldHxProfile.class.getName());

    public static final BDncHandheldHxProfile INSTANCE = new BDncHandheldHxProfile();

    @Override
    public Type getType() {
        return TYPE;
    }

    public static final Type TYPE = Sys.loadType(BDncHandheldHxProfile.class);

    public static AgentFilter makeAgentFilter(String agentTypeSpec) {
        return AgentFilter.is(agentTypeSpec);
    }

    public static String getFilePath(String ord) {
        BOrd fileOrd = BOrd.make(ord);
        OrdQuery[] queries = fileOrd.parse();
        FilePath filePath = (FilePath) queries[queries.length - 1];
        File file = BFileSystem.INSTANCE.pathToLocalFile(filePath);
        return file.getAbsolutePath();
    }

    public static String getStationHomeAbsolutePath() {
        return Sys.getStationHome().getAbsolutePath();
    }

    public static BTlsWebServer getTlsWebServerInstance() {
        StringBuilder bql = new StringBuilder();
        bql.append("station:|slot:/Services|bql:select * from " + Constants.MODULE_NAME + ":TlsWebServer");
        BOrd ord = BOrd.make(bql.toString());
        BITable<BIObject> tlsWebServerTable = (BITable<BIObject>) ord.get(Sys.getStation());
        BTlsWebServer tlsWebServer = null;
        try (TableCursor<BIObject> cursor = tlsWebServerTable.cursor()) {
            while (cursor.next()) {
                tlsWebServer = (BTlsWebServer) cursor.get();
                break;
            }
        }
        return tlsWebServer;
    }

    public static Object getObjectFromBQL(String bql) {
        StringBuilder queryStr = new StringBuilder();
        queryStr.append(bql);
        BOrd ord = BOrd.make(queryStr.toString());
        BITable<BIObject> table = (BITable<BIObject>) ord.get(Sys.getStation());
        Object object = null;
        try (TableCursor<BIObject> cursor = table.cursor()) {
            while (cursor.next()) {
                object = cursor.get();
                break;
            }
        }
        return object;
    }
}
